package com.xdl.flytest.util.runner;

import com.xdl.flytest.util.docker.DockerEnvironmentConfig;
import com.xdl.flytest.util.docker.DockerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;


/**
 * @Auther: 80736
 * @Date: 2019/1/24 16:51
 * @Description: 测试用例运行器
 */

@Component("TestCaseRunner")
public class TestCaseRunner extends BaseRunner {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 运行测试用例
     * 1.创建docker容器，启动容器(初始化）
     * 2.创建httprunner脚手架
     * 3.在容器内创建*.json测试文件，将testcase jsonData写入.json文件
     * 4.通过httprunner命令行运行测试用例 hrun ...
     * 5.获取测试报告并存储到mongodb
     *
     * @param containerId 容器id
     * @param script      测试脚本（json)
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    public void run(String containerId, String script) throws IOException, InterruptedException {

        // 1.如果容器id不为空则开始测试
        if (containerId != null) {
            // 2.创建httprunner脚手架
            DockerManager.createTestProject(containerId, "/home/test");
            // 3.将testcase jsonData写入.json文件.
            String jsonFile = DockerManager.createJsonFile(script);
            logger.debug("write json data to testcase in system temp dir");
            // 4.复制json文件到容器，在容器内指定文件夹创建*.json测试文件.
            DockerManager.copyLocalFile(containerId, jsonFile, "/home/test/testcases/");
            // 5.运行测试
            logger.debug("start testing in docker with httprunner");
            DockerManager.execCmdResult(String.format("docker exec %s hrun %s --report-dir %s", containerId, "/home/test/testcases/", "/home/test/reports/"));
            // 6.获取测试报告复制到宿主机
            DockerManager.copyDockerFile(containerId, "/home/test/reports/", DockerEnvironmentConfig.LOCAL_REPORT_SAVED_PATH);
        } else {
            throw new RuntimeException("init container failed");
        }

    }

}
